// pages/telephone/telephone.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    telephone:'',
    code:'',
    wait:5
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getData();
  },
  getData(){
    var context = this;
    wx.request({
      url: app.config.server + "/api/sms_msg_wait",
      header:{
        sessionkey: wx.getStorageSync('session_key')
      },
      success:function(res){
        context.setData({
          wait: res.data
        })
      }
    })
    if(this.data.wait > 0){
      var limit = setInterval(function(){
        console.log(context.data.wait);
          context.setData({
            wait:context.data.wait - 1
          });
          if(context.data.wait == 0){
            clearInterval(limit);
          }
      },1000)
    }
  },
  inputTelephone: function(e){
    this.setData({
      telephone:e.detail.value
    });
  },
  inputCode: function(e){
    this.setData({
      code:e.detail.value
    })
  },
  tapSend: function(){
    var context = this;
    if(context.data.telephone.length < 11){
      wx.showToast({
        title: '请输入正确的手机号码',
      });
      return false;
    }
    wx.request({
      url: app.config.server + "/api/send_sms",
      method:"POST",
      data:{
        telephone:this.data.telephone
      },
      header:{
        sessionkey:wx.getStorageSync('session_key')
      },
      success: res => {
        console.log(res);
        context.getData();
      }
    })
  },
  tapSubmit: function(e){
    var context = this;
    if(context.data.telephone.length < 11){
      wx.showToast({
        title: '请输入正确的手机号码',
      });
      return false;
    }
    if(context.data.code.length != 4){
      wx.showToast({
        title: '请输入正确的验证码',
      });
      return false;
    }
    wx.request({
      url: app.config.server + "/api/update_telephone",
      method:'POST',
      data:{
        telephone: this.data.telephone,
        code: this.data.code
      },
      header:{
        sessionkey: wx.getStorageSync('session_key')
      },
      success: res => {
        console.log(res);  
        if(res.data.success){
          wx.redirectTo({
            url: '/pages/personal/personal',
            success: res => {
              wx.showToast({
                title: '修改手机号码成功',
              })
            }
          })
        }else{
          wx.showToast({
            title: res.data.message,
          })
        }
      }
    })
  }
})